// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
import evn from "../../utils/http/evn"
Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    url:  evn.dev.baseUrl,
    imgBaseUrl:  evn.dev.imgUrl,
    searchValue: '' // 搜索输入框的值
    
  },
  //搜索输入框输入事件处理
  onSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    });
    console.log('搜索输入值:', e.detail.value);
  },
  goSearch(){
    console.log("1111")
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },


  //搜索图标加载错误处理
  searchIconError(e) {
    console.log('搜索图标加载失败:', e.detail.errMsg)
  },
  goKorea(){
    wx.navigateTo({
      url: '/pages/area/korea/korea',
    })
  },
  goSingapore(){
    wx.navigateTo({
      url: '/pages/area/singapore/singapore',
    })
  },
   goSpain(){
    wx.navigateTo({
      url: '/pages/area/spain/spain',
    })
  },
  goChina(){
    wx.navigateTo({
      url: '/pages/area/china/china',
    })
  },
  goHKandMaCao(){
    wx.navigateTo({
      url: '/pages/area/hkandmacao/hkandmacao',
    })
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  
  //记号 跳转到韩国生活页面
  goToKoreanLive() {
    wx.navigateTo({
  url: '/pages/area/korea/koreanLive'
    })
  },

  //跳转到韩国申请页面
  goToKoreanRequest() {
    wx.navigateTo({
  url: '/pages/area/korea/koreanRequest'
    })
  },

  //Logo图片加载错误处理
  logoError(e) {
    console.log('Logo图片加载失败:', e.detail.errMsg)
  },

  //国家图片加载错误处理
  countryImageError(e) {
    const country = e.currentTarget.dataset.country;
    console.log(`${country}图片加载失败:`, e.detail.errMsg)
  },

  //合作图片加载错误处理
  cooperationImageError(e) {
    const type = e.currentTarget.dataset.type;
    console.log(`${type}图片加载失败:`, e.detail.errMsg)
  },

  //收藏图标加载错误处理
  favoriteIconError(e) {
    console.log('收藏图标加载失败:', e.detail.errMsg)
  },

  //国家专区图片加载错误处理
  countryZoneImageError(e) {
    const type = e.currentTarget.dataset.type;
    console.log(`${type}专区图片加载失败:`, e.detail.errMsg)
  },

  //国旗图片加载错误处理
  flagImageError(e) {
    const type = e.currentTarget.dataset.type;
    console.log(`${type}国旗图片加载失败:`, e.detail.errMsg)
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },

  getPhoneNumber (e) {
    if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
      // 用户点击了取消授权获取手机号码
      wx.reLaunch({
        url: '/pages/index/index',
      })
      this.setData({
        loadingFlag: false
      })
    } else {
      let phoneCode = e.detail.code
      this.login(phoneCode)
    }
  },

  // 登录
  login(phoneCode) {
    wx.login({
      success:(res)=> {
        // wx.showLoading({
        //   title: '登录中',
        // })
        if (res.code) {
          let params = {
            code: res.code,
            phoneCode: phoneCode
          }
          wx.request({
            url: this.data.url + '/user/userLogin',
            method: 'get',
            data: params,
            success: (res => {
              if (res.data.code === 0) {
                // 缓存token
                wx.setStorageSync('token', res.data.data.ID)
                wx.setStorageSync('userInfo', res.data.data)
                this.setData({
                  loadingFlag: false
                })
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
              // wx.hideLoading()
            }),
            fail: (err => {
            })
          })
        } else {
        }
      }
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  // 首页三个国家文本框点击事件
  onSingaporeBoxTap() {
    this.goSingapore();
  },
  onKoreaBoxTap() {
    this.goKorea();
  },
  onSpainBoxTap() {
    this.goSpain();
  },
  onShow() {
    // 开启右上角分享菜单（聊天+朋友圈）
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage'],
    });
  },
  onShareAppMessage() {
    return {
      title: '迪格睿择校助手 x 好好毕业班',
      path: '/pages/index/index?from=share_home'
    };
  },
  onShareTimeline() {
    return {
      title: '迪格睿择校助手 x 好好毕业班',
      query: 'from=share_home'
    };
  },
})
